package middlewares

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	constant "rongyy/src/constants"
	"strconv"
	"strings"
)

func MerchantJwtMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenString := c.GetHeader("AuthorizationMerchant")
		if strings.HasPrefix(c.Request.URL.Path, "/merchant/create") {
			c.Next()
		} else {
			if tokenString == "" {
				c.JSON(401, gin.H{"message": "Missing authorization header"})
				c.Abort()
				return
			}
			tokenString := strings.Replace(tokenString, "Bearer ", "", 1)
			fmt.Println(tokenString)
			token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
				return []byte(constant.JwtSecret), nil // 必须与生成时使用的密钥一致
			})
			fmt.Println(token)
			// 处理解析错误
			if err != nil {
				c.JSON(401, gin.H{"error": "无效 Token1"})
				c.Abort()
				return
			}

			claims, ok := token.Claims.(jwt.MapClaims)
			if ok && token.Valid {
				uid, _ := strconv.ParseInt(fmt.Sprintf("%.0f", claims["merchant_id"]), 10, 64)
				fmt.Println(uid)
				c.Set("merchant_id", uid) // 将 Claims 存入上下文
				c.Next()
			} else {
				c.JSON(401, gin.H{"error": "无效 Token2"})
				c.Abort()
			}
		}
		c.Next()
	}
}
